
#!/bin/bash
# 自动识别架构 + 双下载源保障
NVIM_VERSION="stable"  # 可改为nightly
INSTALL_DIR="/opt/neovim"
TIMEOUT=30

# 架构检测（支持x86_64/aarch64）
case $(uname -m) in
  x86_64)  DOWNLOAD_ARCH="x86_64" ;;
  aarch64) DOWNLOAD_ARCH="arm64"  ;;
  *) 
    echo "❌ 不支持的架构: $(uname -m)" 
    exit 1
    ;;
esac

# 构造下载URL
TAR_URL="https://github.com/neovim/neovim/releases/download/$NVIM_VERSION/nvim-linux-$DOWNLOAD_ARCH.tar.gz"
APPIMAGE_URL="https://github.com/neovim/neovim/releases/download/$NVIM_VERSION/nvim.appimage"

# 安装目录准备
sudo mkdir -p $INSTALL_DIR && sudo chown $USER:$USER $INSTALL_DIR

# 下载策略：优先架构包→超时转AppImage
if curl --fail --connect-timeout $TIMEOUT -L $TAR_URL -o nvim.tar.gz; then
    echo "✅ 成功下载 $DOWNLOAD_ARCH 架构包"
    tar xzf nvim.tar.gz -C $INSTALL_DIR --strip-components 1
    sudo ln -sf $INSTALL_DIR/bin/nvim /usr/local/bin/nvim
    rm nvim.tar.gz
else
    echo "⚠️  架构包下载失败，改用AppImage"
    if curl --fail -L $APPIMAGE_URL -o nvim.appimage; then
        chmod +x nvim.appimage
        sudo mv nvim.appimage /usr/local/bin/nvim
    else
        echo "❌ 全部下载方式失败"
        exit 1
    fi
fi

# 验证安装
nvim --version | head -n1
